<template>
  <div class="route-page">
    <a-card title="公司列表" class="card-with-title-page" size="small">
      <a-table
        :dataSource="dataList"
        :columns="columns"
        :loading="loading"
        rowKey="id"
        :pagination="pagination"
        @change="handleTableChange"
        :row-selection="rowSelection"
        :scroll="{ x: 'max-content' }"
      >
        <template #title>
          <div class="flex justify-between header-clue">
            <div class="flex-1">
              <a-form layout="vertical">
                <a-row :gutter="8">
                  <a-col :span="3">
                    <a-form-item>
                      <a-input
                        placeHolder="请输入公司名称或简称"
                        v-model:value="searchParams.name"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :span="3">
                    <a-form-item>
                      <a-input
                        placeHolder="请输入负责人"
                        v-model:value="searchParams.leader_name"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :span="3">
                    <a-form-item>
                      <a-input
                        placeHolder="请输入联系方式"
                        v-model:value="searchParams.leader_phone"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :span="3">
                    <a-form-item>
                      <a-select
                        style="width: 100%"
                        :allowClear="true"
                        placeholder="请选择状态"
                        v-model:value="searchParams.status"
                        :options="statusOptions"
                      />
                    </a-form-item>
                  </a-col>

                  <a-col :span="3">
                    <a-form-item label="">
                      <a-space>
                        <a-button @click="reset">重置</a-button>
                        <a-button type="primary" @click="getDataList(true)">
                          搜索
                        </a-button>
                      </a-space>
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-form>
            </div>
            <div>
              <a-space>
                <a-button type="primary" ghost @click.stop="handleExport">导出</a-button>
                <a-button type="primary" @click.stop="handleAdd">新增</a-button>
              </a-space>
            </div>
          </div>
        </template>

        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key === 'account_sum'">
            <span class="link" @click.stop="showAccount(record)">
              {{text || 0}}
            </span>
          </template>
          <template v-if="column.key === 'status'">
            <a-switch
              :checkedValue="0"
              :unCheckedValue="1"
              :checked="text"
              checked-children="开启"
              un-checked-children="关闭"
              @click="(checked) => handleStatusClick(record.id, checked)"
            />
          </template>
          <template v-if="column.key === 'action'">
            <a-button type="link" @click.stop="handleEdit(record)">
              编辑
            </a-button>
            <a-button  type="link" danger :disabled="record.is_system == 1"  @click.stop="handleDelete(record)">
              删除
            </a-button>
          </template>
        </template>
      </a-table>
    </a-card>

    <AddCompany
      :visible="addVisible"
      :id="editId"
      @handleCancel="handleAddCancel"
      @handleSuccess="handleAddSuccess"
    />

    <AccountList
      :visible="listVisible"
      :id="listId"
      @handleCancel="listVisible = false"
      @refreshData="getDataList()"
    />
  </div>
</template>

<script>
import {reactive, ref, toRefs, computed, watch, defineComponent, createVNode, onActivated} from "vue";
import { useRoute, useRouter } from "vue-router";
import { TextTip } from "bl-common-vue3";
import store from "@/store";
import {Form, message, Modal} from "ant-design-vue";
const useForm = Form.useForm;
import request from "@/common/utils/request";
import {ExclamationCircleOutlined, FormOutlined} from "@ant-design/icons-vue";
import AddCompany from "@/views/setting/CompanyInfo/modules/AddCompany.vue";
import AccountList from "@/views/setting/CompanyInfo/modules/AccountList.vue";
import _ from "lodash";

const COLUMNS = [
  {
    title: "公司名称",
    align: "center",
    dataIndex: "company",
    key: "company",
    fixed: store.getters.isMobile ? undefined : "left",
    width: 150,
  },
  {
    title: "公司简称",
    align: "center",
    dataIndex: "name",
    key: "name",
    customRender: ({ text }) => {
      return text || '--';
    },
    width: 150,
  },
  {
    title: "纳税识别号",
    align: "center",
    dataIndex: "taxpayer_number",
    key: "taxpayer_number",
    customRender: ({ text }) => {
      return text || '--';
    },
    width: 200,
  },
  {
    title: "绑定部门",
    align: "center",
    dataIndex: "department_name",
    key: "department_name",
    customRender: ({ text }) => {
      return text || '--';
    },
    width: 150,
  },
  {
    title: "负责人",
    align: "center",
    dataIndex: "leader_name",
    key: "leader_name",
    customRender: ({ text }) => {
      return text || '--';
    },
    width: 180,
  },
  {
    title: "联系方式",
    align: "center",
    dataIndex: "leader_phone",
    key: "leader_phone",
    customRender: ({ text }) => {
      return text || '--';
    },
    width: 150,
  },
  {
    title: "公司地址",
    align: "center",
    dataIndex: "address",
    key: "address",
    customRender: ({ text, record }) => {
      return (record?.district_txt || '') + (record?.address || '');
    },
    width: 150,
  },
  {
    title: "收支账户数量",
    align: "center",
    dataIndex: "account_sum",
    key: "account_sum",
    width: 150,
    customRender: ({ text }) => {
      return text || 0;
    },
  },
  {
    title: "状态",
    align: "center",
    dataIndex: "status",
    key: "status",
    width: 150,
  },
  {
    title: "操作",
    align: "center",
    dataIndex: "id",
    key: "action",
    width: 180,
    fixed: "right",
  },
]
export default defineComponent( {
  name: "orgBranchList",
  props: {

  },
  components: {
    FormOutlined,
    TextTip,
    AddCompany,
    AccountList,
  },
  setup(props, { emit }) {
    const $router = useRouter();
    const state = reactive({
      dataList: [],
      columns: COLUMNS,
      loading: false,
      page: 1,
      limit: 10,
      total: 0,
      addVisible: false,
      editId: 0,
      selectedRowKeys: [],
      statusOptions: [
        {
          label: '全部',
          value: 2,
        },
        {
          label: '正常',
          value: 0,
        },
        {
          label: '禁用',
          value: 1,
        },
      ],
      listVisible: false,
      listId: 0,
    });

    const searchParams = reactive({
      name: "", // 联系人名称
      leader_name: "", // 联系人电话
      leader_phone: '', // 公司名称
      status: undefined, // 客户状态
    });



    const onSelectedRowChange = (selectedRowKeys) => {
      state.selectedRowKeys = selectedRowKeys;
    };

    const rowSelection = computed(() => ({
      selectedRowKeys: state.selectedRowKeys,
      onChange: onSelectedRowChange,
    }));
    const { resetFields } = useForm(searchParams, {});

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.limit,
      showSizeChanger: true,
    }));

    const getDataList = (init = false) => {
      state.loading = true;
      if (init) {
        state.page = 1;
        state.selectedRowKeys = [];
      }
      const params = {
        page: state.page,
        pageSize: state.limit,
      };
      for (let key in searchParams) {
        if (searchParams[key] || searchParams[key] === 0) {
          params[key] = searchParams[key];
        }
      }
      request
        .get("/org", "/company/orgBranch", params)
        .then((res) => {
          state.dataList = res?.list || [];
          state.total = res?.total || 0;
        })
        .finally(() => {
          state.loading = false;
        });
    };

    const handleTableChange = (pager) => {
      state.page = pager.current;
      state.limit = pager.pageSize;
      getDataList();
    };

    const reset = () => {
      resetFields();
      getDataList(true)
    };

    // 新增
    const handleAdd = () => {
      state.addVisible = true;
    };

    const handleAddCancel = () => {
      state.addVisible = false;
      state.editId = 0;
    };

    const handleAddSuccess = () => {
      handleAddCancel();
      getDataList();
    };

    const init = () => {
      getDataList(true);
    };

    const handleDelete = (record) => {
      Modal.confirm({
        title: () => "提示",
        content: () => "确定要删除该公司吗？",
        icon: () => createVNode(ExclamationCircleOutlined),
        okText: () => "确定",
        onOk() {
          request
            .del("/org", "/company/orgBranch", {id: record.id})
            .then((res) => {
              message.success(res?.msg || '删除成功');
              state.selectedRowKeys = [];
              getDataList();
            })
        },
      });
    };

    const handleEdit = (record) => {
      state.editId = record?.id || 0;
      state.addVisible = true;
    };

    const handleStatusClick = (id, checked) => {
      request
        .put("/org", "/company/orgBranch/status", {id, status: checked})
        .then((res) => {
          message.success(res?.msg || '修改成功');
          getDataList();
        })
    };

    const showAccount = (record) => {
      state.listId = record?.id || 0;
      state.listVisible = true;
    };

    // 导出报表
    let timer = null;
    const iframe = document.createElement("iframe");
    const handleExport = () => {
      if (timer) {
        message.warn("操作过于频繁，请稍后尝试");
        return;
      }
      let params = {
        ids: state.selectedRowKeys.join(','),
      };
      for (let key in searchParams) {
        if (searchParams[key] || searchParams[key] === 0) {
          params[key] = searchParams[key];
        }
      }
      request
        .post("/org", "/company/exportCompany", params)
        .then((res) => {
          iframe.src = res.result.fileUrl;
          iframe.style.display = "none";
          document.body.appendChild(iframe);
          setTimeout(() => {
            document.body.removeChild(iframe);
          }, 1000);
          message.success("导出成功,请等待文件生成");
          timer = setTimeout(() => {
            timer = null;
          }, 20000);
        });
    };

    onActivated(() => {
      init();
    });

    return {
      ...toRefs(state),
      pagination,
      searchParams,
      rowSelection,
      handleTableChange,
      reset,
      getDataList,
      handleAdd,
      handleAddSuccess,
      handleAddCancel,
      handleDelete,
      handleEdit,
      handleExport,
      handleStatusClick,
      showAccount,
    };
  },
});

</script>

<style lang="less" scoped>
.route-page .card-with-title-page {
  padding: 0 0 7px 0;
}
:deep(.ant-card-small > .ant-card-head) {
  height: 49px;
  min-height: initial;
}
:deep(.ant-card-head-wrapper) {
  height: 100%;
}
:deep(.ant-table-title) {
  padding: 6px 0;
}
</style>
